import { SLIT_INFO_NAME, UNIT_TO_M, WHOLE_ROLL_INFO } from '@/utils/constant';
import { Button, Input, Spin } from 'antd';
import React, { Ref, useEffect, useRef, useState } from 'react';

import FlawFilterDialog from '@/components/FlawFilter/index';
import './index.less';

import { handleSlitInfo } from '../../script/tool';
import { doffInfoT, slitListT } from '../../type';
import { useNavigate, useLocation } from 'react-router-dom';
import { useStores } from '@/stores';
import { MessageWaring, onlyGetChildFlaw, onlyGetChildFlawDoff } from '@/utils/tool';
import { FlawFilterDialogT, FlawFilterType, MapLayerSelectT } from '@/typings/global';
import { getQueryMapLayer } from '@/api/map-page';
import { Storage } from '@/utils/storage';
import FlawFilterPmp from '@/components/FlawFilterPmp';

export interface RollTableConf {
  onRef?: Ref<any> | undefined;
  layerIdSearch: (info: object) => void; // 查询提交
}

const RollTable: React.FC<RollTableConf> = (rollProp: RollTableConf) => {
  const { sysMapStore, commonStore } = useStores();
  const navigate = useNavigate();
  const location = useLocation();
  const flawFilterRef = useRef<any>(null);
  const flawRef = useRef<any>(null);
  const [spinState, setSpinState] = useState<boolean>(false);
  const [layerId, setLayerId] = useState<string>();
  const [doffData, setDoffData] = useState<doffInfoT>({} as doffInfoT); //涂层的整卷信息
  const [slitData, setSlitData] = useState<Array<slitListT>>([]); // 分条信息-->进行处理用于页面展示

  useEffect(() => {
    // 在路由进入时执行的逻辑
    setLayerId(Storage.get('searchLayerID'));
    if (Storage.get('searchLayerID')) {
      searchLayer();
    }
  }, [location]);

  const searchLayer = async () => {
    const currentLayerId = layerId ? layerId : Storage.get('searchLayerID');
    const isPass = checkQueryParamsPass(currentLayerId);
    if (!isPass) {
      MessageWaring('查询的条件不能为空！！！');
      return;
    }
    setSpinState(true);
    if (Storage.get('searchLayerID') !== currentLayerId) {
      //存储当前的搜索的涂层批号
      Storage.set('searchLayerID', currentLayerId);
    }
    const newPArams = handleQueryParams(sysMapStore, commonStore, currentLayerId);
    // console.log('传给后端的参数---图层', newPArams);
    // setSpinState(false);
    // return;
    const backMap = await getQueryReqData(newPArams);
    setSpinState(false);
    if (JSON.stringify(backMap) === '{}') {
      MessageWaring('涂层数据不存在!');
      setSlitData([]);
      setDoffData({} as doffInfoT);
      rollProp.layerIdSearch({});
      return;
    }
    // 拿到数据之后，重新去画缺陷地图的数据
    rollProp.layerIdSearch({
      rect: backMap.lotList,
      dot: backMap.flawList,
      osAvoidance: backMap.osAvoidance,
      dsAvoidance: backMap.dsAvoidance,
      height: backMap.height,
      width: backMap.width,
      layerQrMd: backMap.layerQrMd,
      commonStore: commonStore
    });

    // setSlitData
    setSlitData(handleSlitInfo(backMap.lotList)); // 分条数据
    // 卷长和幅宽保留两位小数
    backMap.height = backMap.height?.toFixed(2);
    backMap.width = backMap.width?.toFixed(2);
    // setDoffData
    setDoffData(backMap);
  };

  const checkQueryParamsPass = (layerId: string) => {
    if (layerId && layerId.trim()) {
      return true;
    } else {
      return false;
    }
  };

  // 处理查询参数
  const handleQueryParams = (sysMapStore, commonStore, layerId: string): MapLayerSelectT => {
    let newParams = {
      //   layerId:layerId,
      layerId: layerId.trim(), // 输入框-去除空格
      flawTypeList: {
        doff: [],
        pol: [],
        piantiehou: []
      }
    } as any;

    const pol = sysMapStore.flawTypeStorage.pol;
    const piantiehou = sysMapStore.flawTypeStorage.piantiehou;
    newParams.flawTypeList.doff = sysMapStore.checkedFlawTypePmp;

    if (pol.length && pol[0] !== 'all') {
      newParams.flawTypeList.pol = onlyGetChildFlaw(pol, commonStore.polResult.fatherMap);
    } else if (pol.length && pol[0] === 'all') {
      delete newParams.flawTypeList.pol;
    }

    if (piantiehou.length && piantiehou[0] !== 'all') {
      newParams.flawTypeList.piantiehou = onlyGetChildFlaw(piantiehou, commonStore.pianResult.fatherMap);
    } else if (piantiehou.length && piantiehou[0] === 'all') {
      delete newParams.flawTypeList.piantiehou;
    }

    if (!Object.keys(newParams.flawTypeList).length) {
      delete newParams.flawTypeList;
    }

    return newParams;
  };

  const getQueryReqData = async queryParams => {
    try {
      const resback = await getQueryMapLayer(queryParams);
      return resback;
    } catch (error) {
      console.log(error);
    }
    return {};
  };

  //   缺陷筛选
  const openFlawFilter = () => {
    flawFilterRef.current.setShowFiledDialog(true);
  };

  // 跳转到详情页
  const gotoDetail = lotInfo => {
    console.log('gotoDetail--->', lotInfo);
    const path = `/detail/${lotInfo.lotId}`;
    navigate(path);
  };

  //   打开前制程缺陷筛选的Dialog
  const openPmpFlaw = () => {
    console.log('点击--打开--对话框');
    flawRef?.current.showModal();
  };
  return (
    <>
      {/* 查询组件 */}
      {/* 统计信息--整卷信息 */}
      {/* 分卷信息-- */}
      <div className="roll-info">
        <div className="search-bar">
          涂层批号：
          <Input
            className="layer-id-input"
            allowClear={true}
            value={layerId}
            onChange={val => {
              setLayerId(val.target.value);
            }}
            width={200}
          ></Input>
          {/* <Input defaultValue={'tucheng01'} ref={layerIdRef} placeholder={'请输入涂层批号'} style={{ width: '280px', marginRight: '10px' }} /> */}
          <Button type={'primary'} onClick={searchLayer} className="btn">
            查询
          </Button>
          <Button type={'primary'} onClick={() => openFlawFilter()} className="btn">
            缺陷筛选
          </Button>
        </div>
        <Spin size="large" tip="加载中..." spinning={spinState}>
          <div className="title">1 整卷信息</div>
          <div className="whole-roll">
            {WHOLE_ROLL_INFO.map((item: { name: string; key: string; width: number; unit: string }, index) => (
              <div style={{ width: item.width }} key={`whole-roll-${index}`}>
                {item.name}：{doffData[item.key] ? (item.key === 'height' ? (doffData[item.key] / UNIT_TO_M)?.toFixed(2) : doffData[item.key]) : item.unit ? '0' : ''} {item.unit}
              </div>
            ))}
          </div>
          <div className="title">2 分卷信息</div>
          <div className="split-roll">
            {slitData.map((item: any, index) => (
              <div className="group" key={`split-roll-${index}`}>
                <div>
                  {SLIT_INFO_NAME.lotId}：{item['lotId']}
                </div>
                <div>
                  {SLIT_INFO_NAME.TD_between}：{item['TD_between']}
                </div>
                <div>
                  {SLIT_INFO_NAME.MD_between}：{item['MD_between']}
                </div>
                <div>
                  {SLIT_INFO_NAME.dimensions_between}：{item['dimensions_between']}
                </div>
                <div>
                  {SLIT_INFO_NAME.oneCut}：{item['oneCut'] || 0}
                </div>
                <div>
                  {SLIT_INFO_NAME.yield}：{(item['yield'] * 100).toFixed(2) || 0}%
                </div>
                <div>
                  {SLIT_INFO_NAME.okRatio}：{(item['okRatio'] * 100).toFixed(2) || 0}%
                </div>
                <div>
                  {SLIT_INFO_NAME.areaUseRatoi}：{(item['areaUseRatio'] * 100).toFixed(2) || 0}%
                </div>
                <div>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => {
                      gotoDetail(item);
                    }}
                  >
                    详情
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </Spin>
        <FlawFilterDialog onRef={flawFilterRef} type={FlawFilterDialogT.layerId} onSubmit={searchLayer} openPmpFlaw={openPmpFlaw}></FlawFilterDialog>
        <FlawFilterPmp onRef={flawRef} type={FlawFilterType.map}></FlawFilterPmp>
      </div>
    </>
  );
};

export default RollTable;
